#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QListWidgetItem>
#include <QBuffer>
#include <QByteArray>
#include <QPainter>
#include <QRect>

#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ipFliter = "" ;
    sf = false ;
    uc = new QUdpSocket() ;
    uc->bind( QHostAddress::AnyIPv4 , 51023 ) ;
    qDebug() << uc->state() ;

    connect( uc , &QUdpSocket::readyRead , this , &MainWindow::readPendingDatagram ) ;
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::readPendingDatagram() {
    while ( uc->hasPendingDatagrams() ) {
        QNetworkDatagram datagram = uc->receiveDatagram() ;
        showVideoframe( datagram ) ;
        insertDevicesList( datagram.senderAddress().toString() ) ;
    }
}


void MainWindow::insertDevicesList( const QString &address ) {
    if ( ui->devicesList->findItems( address , Qt::MatchFixedString ).size() < 1 )
        ui->devicesList->addItem( address ) ;
}

void MainWindow::showVideoframe(const QNetworkDatagram &datagram) {
    if ( ipFliter != datagram.senderAddress().toString() ) return ;
    img.loadFromData( QByteArray::fromBase64( datagram.data() ) ) ;
    this->QWidget::update() ;
}

void MainWindow::on_updateList_clicked() {
    ui->devicesList->clear() ;
}


void MainWindow::on_devicesList_itemClicked(QListWidgetItem *item) {
    ipFliter = item->text() ;
}

#ifdef PAINT_EVENT
void MainWindow::paintEvent(QPaintEvent *ev) {
    if ( !sf ) return ;
    QPainter painter(this) ;
    auto &&pos = ui->videoWidget->pos() ;
    auto &&size = ui->videoWidget->size() ;
    painter.drawImage( QRect( pos.x() , pos.y() , size.width() , size.height() ) , img.mirrored(true,true) ) ;
}
#endif


void MainWindow::on_start_clicked() {
    sf = true ;
}


void MainWindow::on_stop_clicked() {
    sf = false ;
}


void MainWindow::on_setPort_clicked() {
    uc->bind( QHostAddress::AnyIPv4 , ui->inputPort->text().toInt() ) ;
}

